package com.css.fxfzaqbz.modules.base.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.css.fxfzaqbz.base.response.RestResponse;
import com.css.fxfzaqbz.common.utils.BeanUtil;
import com.css.fxfzaqbz.common.utils.EasyPoiExcelUtil;
import com.css.fxfzaqbz.constants.FxfzConstants;
import com.css.fxfzaqbz.modules.base.entity.BuildingVulnerability;
import com.css.fxfzaqbz.modules.base.entity.ExcelEntity;
import com.css.fxfzaqbz.modules.base.queryParams.BuildingVulnerabilityQueryParams;
import com.css.fxfzaqbz.modules.base.repository.BuildingVulnerabilityRepository;
import com.css.fxfzaqbz.modules.base.service.BuildingVulnerabilityService;
import com.css.fxfzaqbz.util.*;
import com.css.fxfzaqbz.web.PlatformSessionContext;
import com.css.fxfzaqbz.zcpt.sys.entity.SUser;
import com.css.fxfzaqbz.zcpt.sys.service.SUserService;
import com.css.fxfzaqbz.zcpt.sys.service.SysAreaService;
import com.css.fxfzaqbz.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Service
public class BuildingVulnerabilityServiceImpl implements BuildingVulnerabilityService {
    @Resource
    BuildingVulnerabilityRepository buildingVulnerabilityRepository;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SUserService sUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<BuildingVulnerability> getPage(BuildingVulnerability buildingVulnerability) {
        List<BuildingVulnerability> page = buildingVulnerabilityRepository.getPage(buildingVulnerability);
        if (page.size() != 0) {
            return page;
        }
        ArrayList<BuildingVulnerability> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            BuildingVulnerability vulnerability = new BuildingVulnerability();
            BeanUtil.copyPropertiesIgnoreEmpty(buildingVulnerability, vulnerability);
            vulnerability.setDestroy("" + i);
            vulnerability.setIntensity("6度");
            vulnerability.setIsNull("0");
            vulnerability.setCreateUser(PlatformSessionUtils.getUserId());
            vulnerability.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            list.add(vulnerability);
            vulnerability.setId(UUIDGenerator.getUUID());
            buildingVulnerabilityRepository.save(vulnerability);
        }
        for (BuildingVulnerability vulnerability : list) {
            vulnerability.setIntensity("7度");
            vulnerability.setId(UUIDGenerator.getUUID());
            buildingVulnerabilityRepository.save(vulnerability);
        }
        for (BuildingVulnerability vulnerability : list) {
            vulnerability.setIntensity("8度");
            vulnerability.setId(UUIDGenerator.getUUID());
            buildingVulnerabilityRepository.save(vulnerability);
        }
        for (BuildingVulnerability vulnerability : list) {
            vulnerability.setIntensity("9度");
            vulnerability.setId(UUIDGenerator.getUUID());
            buildingVulnerabilityRepository.save(vulnerability);
        }
        for (BuildingVulnerability vulnerability : list) {
            vulnerability.setIntensity("未设防");
            vulnerability.setId(UUIDGenerator.getUUID());
            buildingVulnerabilityRepository.save(vulnerability);
        }
        for (BuildingVulnerability vulnerability : list) {
            vulnerability.setIntensity("无设防信息");
            vulnerability.setId(UUIDGenerator.getUUID());
            buildingVulnerabilityRepository.save(vulnerability);
        }
        List<BuildingVulnerability> page1 = buildingVulnerabilityRepository.getPage(buildingVulnerability);
        return page1;
    }


    @Override
    public void update(List<BuildingVulnerability> list) {
        for (BuildingVulnerability buildingVulnerability : list) {
            buildingVulnerability.setUpdateTime(new Date());
            buildingVulnerability.setUpdateUser(PlatformSessionContext.getUserID());
            buildingVulnerability.setIsNull("1");
            buildingVulnerabilityRepository.update(buildingVulnerability);
        }
    }

    @Override
    public void exportExcel(HttpServletResponse response, BuildingVulnerability buildingVulnerability) {
        List<BuildingVulnerability> list = buildingVulnerabilityRepository.getPage(buildingVulnerability);
        for (BuildingVulnerability item : list) {
            item.setStructureType(castType(item.getStructureType()));
            item.setDestroy(destroy(item.getDestroy()));
        }
        if (list == null || list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        try {
            EasyPoiExcelUtil.exportExcel(list, "建筑物易损性数据信息统计", "建筑物易损性数据信息", BuildingVulnerability.class, "建筑物易损性数据信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public RestResponse save(BuildingVulnerability vulnerability) {
        List<BuildingVulnerability> list = buildingVulnerabilityRepository.getPage(vulnerability);
        for (BuildingVulnerability buildingVulnerability : list) {
            if (!"1".equals(buildingVulnerability.getIsNull())) {
                return RestResponse.fail("保存失败，请确定 " + castType(buildingVulnerability.getStructureType()) + " 类型下都有数值");
            }
        }
        if (list.size() == 300) {
            return RestResponse.succeed();
        }
        int a = 0;
        int b = 0;
        int c = 0;
        int d = 0;
        int e = 0;
        int f = 0;
        int g = 0;
        int l = 0;
        int i = 0;
        int j = 0;
        for (BuildingVulnerability buildingVulnerability : list) {
            if ("0".equals(buildingVulnerability.getStructureType())) {
                a++;
            }
            if ("1".equals(buildingVulnerability.getStructureType())) {
                b++;
            }
            if ("2".equals(buildingVulnerability.getStructureType())) {
                c++;
            }
            if ("3".equals(buildingVulnerability.getStructureType())) {
                d++;
            }
            if ("4".equals(buildingVulnerability.getStructureType())) {
                e++;
            }
            if ("5".equals(buildingVulnerability.getStructureType())) {
                f++;
            }
            if ("6".equals(buildingVulnerability.getStructureType())) {
                g++;
            }
            if ("7".equals(buildingVulnerability.getStructureType())) {
                l++;
            }
            if ("8".equals(buildingVulnerability.getStructureType())) {
                i++;
            }
            if ("9".equals(buildingVulnerability.getStructureType())) {
                j++;
            }
        }
        StringBuilder errMessage = new StringBuilder();
        errMessage.append("保存失败<br/>");
        if (a == 0) {
            errMessage.append("请确定 " + castType("0") + " 类型下都有数值<br/>");
        }
        if (b == 0) {
            errMessage.append("请确定 " + castType("1") + " 类型下都有数值<br/>");
        }
        if (c == 0) {
            errMessage.append("请确定 " + castType("2") + " 类型下都有数值<br/>");
        }
        if (d == 0) {
            errMessage.append("请确定 " + castType("3") + " 类型下都有数值<br/>");
        }
        if (e == 0) {
            errMessage.append("请确定 " + castType("4") + " 类型下都有数值<br/>");
        }
        if (f == 0) {
            errMessage.append("请确定 " + castType("5") + " 类型下都有数值<br/>");
        }
        if (g == 0) {
            errMessage.append("请确定 " + castType("6") + " 类型下都有数值<br/>");
        }
        if (l == 0) {
            errMessage.append("请确定 " + castType("7") + " 类型下都有数值<br/>");
        }
        if (i == 0) {
            errMessage.append("请确定 " + castType("8") + " 类型下都有数值<br/>");
        }
        if (j == 0) {
            errMessage.append("请确定 " + castType("9") + " 类型下都有数值<br/>");
        }
        return RestResponse.fail(errMessage.toString());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse importExcel(MultipartFile file, BuildingVulnerability buildingVulnerability) throws IOException {
        List<ExcelEntity> entities = null;
        try {
            entities = ExcelReaderUtil.readExcelBean(file.getInputStream(), ExcelEntity.class);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        if (entities.size()==0){
            return RestResponse.succeed("导入失败,请选择正确的模板");
        }
        for (int i = 0; i < 30; i++) {
            if (i < 5) {
                entities.get(i).setA("6度");
            }
            if (i >= 5 && i < 10) {
                entities.get(i).setA("7度");
            }
            if (i >= 10 && i < 15) {
                entities.get(i).setA("8度");
            }
            if (i >= 15 && i < 20) {
                entities.get(i).setA("9度");
            }
            if (i >= 20 && i < 25) {
                entities.get(i).setA("未设防");
            }
            if (i >= 25 && i < 30) {
                entities.get(i).setA("无设防信息");
            }
        }
        ArrayList<BuildingVulnerability> vulnerabilities = new ArrayList<>();
        for (ExcelEntity entity : entities) {
            if (entity.getDestroy().equals("基本完好")) {
                entity.setDestroy("0");
            }
            if (entity.getDestroy().equals("轻微破坏")) {
                entity.setDestroy("1");
            }
            if (entity.getDestroy().equals("中等破坏")) {
                entity.setDestroy("2");
            }
            if (entity.getDestroy().equals("严重破坏")) {
                entity.setDestroy("3");
            }
            if (entity.getDestroy().equals("损坏")) {
                entity.setDestroy("4");
            }
            BuildingVulnerability vulnerability = new BuildingVulnerability();
            vulnerability.setDestroy(entity.getDestroy());
            vulnerability.setIntensity(entity.getA());
            try {
                BigDecimal decimal1 = new BigDecimal(entity.getSix()).setScale(2);
                vulnerability.setSix(decimal1);
                BigDecimal decimal2 = new BigDecimal(entity.getSeven()).setScale(2);
                vulnerability.setSeven(decimal2);
                BigDecimal decimal3 = new BigDecimal(entity.getEignt()).setScale(2);
                vulnerability.setEight(decimal3);
                BigDecimal decimal4 = new BigDecimal(entity.getNine()).setScale(2);
                vulnerability.setNine(decimal4);
                BigDecimal decimal5 = new BigDecimal(entity.getTen()).setScale(2);
                vulnerability.setTen(decimal5);
            } catch (NullPointerException e) {
                return RestResponse.succeed("导入失败,所有数值都不能为空");
            } catch (Exception e) {
                return RestResponse.succeed("导入失败,请检查所有输入都为数值");
            }
            vulnerabilities.add(vulnerability);
        }
        BigDecimal[] bigDecimals1 = new BigDecimal[vulnerabilities.size()];
        BigDecimal[] bigDecimals2 = new BigDecimal[vulnerabilities.size()];
        BigDecimal[] bigDecimals3 = new BigDecimal[vulnerabilities.size()];
        BigDecimal[] bigDecimals4 = new BigDecimal[vulnerabilities.size()];
        BigDecimal[] bigDecimals5 = new BigDecimal[vulnerabilities.size()];
        for (int i = 0; i < vulnerabilities.size(); i++) {
            bigDecimals1[i] = vulnerabilities.get(i).getSix();
            bigDecimals2[i] = vulnerabilities.get(i).getSeven();
            bigDecimals3[i] = vulnerabilities.get(i).getEight();
            bigDecimals4[i] = vulnerabilities.get(i).getNine();
            bigDecimals5[i] = vulnerabilities.get(i).getTen();
        }
        for (int j = 0; j < 30; j = j + 5) {
            BigDecimal a = new BigDecimal("0.00");
            BigDecimal b = new BigDecimal("0.00");
            BigDecimal c = new BigDecimal("0.00");
            BigDecimal d = new BigDecimal("0.00");
            BigDecimal e = new BigDecimal("0.00");
            for (int i = j; i < j + 5; i++) {
                a = a.add(bigDecimals1[i]);
                b = b.add(bigDecimals2[i]);
                c = c.add(bigDecimals3[i]);
                d = d.add(bigDecimals4[i]);
                e = e.add(bigDecimals5[i]);
            }
            BigDecimal x = new BigDecimal("1.00");
            int i1 = x.compareTo(a);
            String q = null;
            if (j == 0) {
                q = "6度";
            }
            if (j == 5) {
                q = "7度";
            }
            if (j == 10) {
                q = "8度";
            }
            if (j == 15) {
                q = "9度";
            }
            if (j == 20) {
                q = "未设防";
            }
            if (j == 25) {
                q = "无设防信息";
            }
            if (i1 != 0) {
                return ResponseCreator.createSuccessResponse("导入失败，设法烈度为" + q + "，地震烈度为VI的情况下，破坏程度相加不为1");
            }
            int i2 = x.compareTo(b);
            if (i2 != 0) {
                return ResponseCreator.createSuccessResponse("导入失败，设法烈度为" + q + "，地震烈度为VII的情况下，破坏程度相加不为1");
            }
            int i3 = x.compareTo(c);
            if (i3 != 0) {
                return ResponseCreator.createSuccessResponse("导入失败，设法烈度为" + q + "，地震烈度为VIII的情况下，破坏程度相加不为1");
            }
            int i4 = x.compareTo(d);
            if (i4 != 0) {
                return ResponseCreator.createSuccessResponse("导入失败，设法烈度为" + q + "，地震烈度为IX的情况下，破坏程度相加不为1");
            }
            int i5 = x.compareTo(e);
            if (i5 != 0) {
                return ResponseCreator.createSuccessResponse("导入失败，设法烈度为" + q + "，地震烈度为X的情况下，破坏程度相加不为1");
            }
        }
        buildingVulnerabilityRepository.delete(buildingVulnerability);
        for (BuildingVulnerability vulnerability : vulnerabilities) {
            vulnerability.setProvince(buildingVulnerability.getProvince());
            vulnerability.setCity(buildingVulnerability.getCity());
            vulnerability.setStructureType(buildingVulnerability.getStructureType());
            vulnerability.setPrefecture(buildingVulnerability.getPrefecture());
            vulnerability.setId(UUIDGenerator.getUUID());
            vulnerability.setCreateUser(PlatformSessionUtils.getUserId());
            vulnerability.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            vulnerability.setIsNull("1");
            buildingVulnerabilityRepository.save(vulnerability);
        }
        return ResponseCreator.createSuccessResponse("导入成功");
    }


    /**
     * 结构
     *
     * @param type
     * @return
     */
    private String castType(String type) {
        if (FxfzConstants.TUMU_STRUCTURE.equals(type)) {
            type = "土木/石木结构";
        }
        if (FxfzConstants.QITI_STRUCTURE.equals(type)) {
            type = "砌体结构";
        }
        if (FxfzConstants.MU_STRUCTURE.equals(type)) {
            type = "木结构";
        }
        if (FxfzConstants.YAOT_STRUCTURE.equals(type)) {
            type = "窑洞";
        }
        if (FxfzConstants.GJHNT_STRUCTURE.equals(type)) {
            type = "钢筋混凝土结构";
        }
        if (FxfzConstants.MUZHU_STRUCTURE.equals(type)) {
            type = "木（竹）结构";
        }
        if (FxfzConstants.HZ_STRUCTURE.equals(type)) {
            type = "混杂结构";
        }
        if (FxfzConstants.GANG_STRUCTURE.equals(type)) {
            type = "钢结构";
        }
        if (FxfzConstants.OTHER_STRUCTURE.equals(type)) {
            type = "其他结构";
        }
        if (FxfzConstants.KZQQT_STRUCTURE.equals(type)) {
            type = "底部框架-抗震墙砌体结构";
        }
        return type;
    }

    /**
     * 结构
     *
     * @param type
     * @return
     */
    private String destroy(String type) {
        if ("0".equals(type)) {
            type = "基本完好";
        }
        if ("1".equals(type)) {
            type = "轻微破坏";
        }
        if ("2".equals(type)) {
            type = "中等破坏";
        }
        if ("3".equals(type)) {
            type = "严重破坏";
        }
        if ("4".equals(type)) {
            type = "损坏";
        }
        return type;
    }

}
